package com.xszx.server.service;

import com.xszx.server.dto.Page;
import com.xszx.server.entity.Section;
import com.xszx.server.mapper.CourseMapper;
import com.xszx.server.mapper.SectionMapper;
import com.xszx.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SectionService {
    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private CourseMapper courseMapper;

    /**
     * 获取分页列表
     * @param page
     * @return
     */
    public Page getAllSections(Page page){
        int pageNum = page.getPage();
        page.setPage((page.getPage()-1)*page.getSize());
        page.setList(sectionMapper.findAll(page));
        page.setTotal(sectionMapper.findCount());
        page.setPage(pageNum);
        return page;
    }
    /**
     * 获取课程小节列表
     * @param courseId
     * @return
     */
    public List<Section> getSectionsByCourse(String courseId){
        return sectionMapper.findSectionsByCourse(courseId);
    }

    /**
     * 新增或者删除信息
     * @param section
     * @return
     */
    @Transactional
    public String saveOrUpdate(Section section){
        String result = "";
        if(StringUtils.isEmpty(section.getId())){
            Date now = new Date();
            section.setCreatedAt(now);
            section.setUpdatedAt(now);
            section.setId(UuidUtil.getShortUuid());
            result = (sectionMapper.insert(section)>0)?"添加成功":"添加失败";
            //更新课程的时间
            courseMapper.updateTime(section.getCourseId());
            return result;
        }else{
            section.setUpdatedAt(new Date());
            result = (sectionMapper.updateByPrimaryKey(section)>0)?"更新成功":"更新失败";
            //更新课程的时间
            courseMapper.updateTime(section.getCourseId());
            return result;
        }
    }

    /**
     * 物理删除小节
     * @param id
     * @return
     */
    @Transactional
    public int del(String id){
        Section section = sectionMapper.selectByPrimaryKey(id);
        int result = sectionMapper.deleteByPrimaryKey(id);
        //更新课程的时间
        courseMapper.updateTime(section.getCourseId());
        return result;
    }
     /**
     * 获取单个小节
     * @return
     */
    public Section getSection(String id){
        return sectionMapper.selectByPrimaryKey(id);
    }
}
